using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Xml;
using GGEditor.API;
using GGEditor.API.Plugins;
using GGEditor.Core.Commands;

namespace GGEditor.Core.UI
{
	[XmlNodeObjectFactory(Name = "MenuItem")]
	public class MenuItemFactory : IXmlNodeObjectFactory
	{
		#region Implementation of IXmlNodeObjectFactory

		public virtual object Build(IPluginNode pluginNode, IDictionary<string, string> attributes)
		{
			pluginNode.ChildAdded += OnChildAdded;
			pluginNode.ChildRemoved += OnChildRemoved;

			string label = pluginNode.Name;
			if (attributes.ContainsKey("label"))
				label = attributes["label"];

			ToolStripMenuItem menuItem = new ToolStripMenuItem(label);

			if (attributes.ContainsKey("command"))
			{
				string commandName = attributes["command"];

				menuItem.Click += delegate(object o, EventArgs e)
				{
					//CommandManager.Instance.DoCommand(commandName);
				};
			}

			menuItem.Tag = pluginNode;
			menuItem.DropDownOpening += OnDropDownOpening;

			return menuItem;
		}

		void OnDropDownOpening(object sender, EventArgs e)
		{
			ToolStripMenuItem menuItem = sender as ToolStripMenuItem;
			if (menuItem == null)
				return;

			menuItem.DropDownItems.Clear();

			IPluginNode pluginNode = menuItem.Tag as IPluginNode;
			if (pluginNode == null)
				return;

			foreach (IPluginNode childNode in pluginNode.Nodes)
			{
				if (childNode.State == PluginNodeState.Hidden)
					continue;
				ToolStripItem childItem = childNode.Object as ToolStripItem;
				if (childItem == null)
					continue;
				menuItem.Enabled = childNode.State == PluginNodeState.Enabled;
				menuItem.DropDownItems.Add(childItem);
			}
		}

		void OnChildAdded(IPluginNode node, IPluginNode child, int position)
		{
			//(node.Object as ToolStripMenuItem).DropDownItems.Insert(position, child.Object as ToolStripItem);
		}

		void OnChildRemoved(IPluginNode node, IPluginNode child, int position)
		{
			//(node.Object as ToolStripMenuItem).DropDownItems.RemoveAt(position);
		}

		#endregion
	}
}